import { RedEnvelopeOutlined ,DotChartOutlined, UserOutlined, SearchOutlined,  ArrowLeftOutlined, ArrowRightOutlined, SendOutlined} from '@ant-design/icons'
import { Button,  Skeleton, Space,  Dropdown, Menu,Popover, Carousel,Avatar, BackTop, Modal, Rate, message } from 'antd'
import { useStore } from '../../mobx';
import dayjs from 'dayjs';
import React, {  useEffect, useState } from 'react';
import {  Outlet, useNavigate } from 'react-router-dom';
import Loading from '../../components/Loading'

import Inputs from '../../components/Inputs'
import Img from '../../assets/2.png'
import './index.scss'
import { getToken, supabase, removeToken, setToken } from '../../utils'
import FourGrid from '../../components/FourGrid';
import SectionTitle from '../../components/SectionTitle';
import TextArea from 'antd/lib/input/TextArea';
import axios from 'axios';


const starttext=['好','很好','非常好','超级好','好得不得了了啦']  //打分提示文本
function Home() {
    

  const navi=useNavigate()
  const {userinformation,logincoking}=useStore()  //拉取方法
  const [loading,setloading]=useState(false)  //页面加载loading
  const [modal1Open, setModal1Open] = useState(false);  //建议框显示与隐藏
  const [start,setstart]=useState(3)  //打分
  const [proposaltext,setproposaltext]=useState('')  //建议内容
  const [headerloading,setheaderloading]=useState(false)//头部搜索loading
  const [searchstate,setsearchstate]=useState(false)  //实时更新搜索历史记录状态
  const [historydata,sethistorydata]=useState([])  //观看历史记录
  const [HotData,setHotData]=useState([]) //热门搜索数据
  const [userData,setuserData]=useState({}) //用户信息
  const [RotationImg,setRotationImg]=useState([])//轮播图图片
  const [recommendedcard,setrecommendedcard]=useState([]) //推荐卡数据
  const [ContentData,setContentData]=useState({
    contentHighestscore:[],
    contentCausedepression:[],
    contentfavourite:[],
    contentViolation:[]
  }) //内容区所有数据

  const [chatloading,setchatloading]=useState(false)  //聊天框loading
  const [chatdata,setchatdata]=useState('')  //聊天框状态
  const [chat,setchat]=useState([])//聊天框数据
  // 获取用户信息
  async function usermessage(){
    // console.log(userinformation.information);
    const user=JSON.parse(getToken('user'))
    // console.log(user);
     const {data}=await userinformation.getinformation(user)
    //  console.log(res,'数据');
     setuserData(data[0])
    // console.log(res)
    // 获取观看历史记录
    gethistorydata(data)
     

  }

  async function gethistorydata(data){
    const a=data[0]
     console.log(data,'histroy数据')
    try {
    console.log('histroy报错1')

      if(!a.history) return
    } catch (error) {
    console.log('histroy报错2')

      return
      
    }
    console.log('histroy报错3')
     const b=a.history.split('/')
    //  console.log(b)

     let r=[]

    b.forEach(async item=>{
      if(item=='') return
       let arr=item.split(',')

       const {data,err}=await supabase
       .from('AllData')
       .select('*')
       .eq('id',arr[0])
        // p.push(data[0])
    //    console.log(data)

      
        r.push({...data[0],time:arr[1]})
      // console.log(r)
      //sethistorydata可优化，放在循环里会反复更新状态，放在外边会比循环先执行，获取不到数据
      sethistorydata([...r])
     })
    //  sethistorydata([...r])  

  
  }

// 发送建议
async function proposal(){
  const {data,error}=await supabase.from('proposal').insert([
    {username:userData.username,text:proposaltext,score:start,time:dayjs().format('YYYY-MM-DD HH:mm')}
  ])
  if(data){
    message.success('发送成功', [1],()=>setModal1Open(false))
    return
  }
  message.error('发送失败', [1])
}

  const menu = (
    <Menu
      items={[
        {
          label: '我的信息',
          key: '1',
          icon: <UserOutlined />,
          onClick:()=>navi('/user')
        },
        {
          label: '后台管理',
          key: '2',
          icon: <UserOutlined />,
          onClick:()=>window.open('http://stbackstage.cn3v.work','_blank')
        },
        {
          label: '退出登录',
          key: '3',
          icon: <UserOutlined />,
          onClick:()=>{
            Modal.confirm({
              maskClosable:true,
              cancelText:'取消',
              okCancel:'确认',
              content:'确认退出？',
              onOk:()=>{
                logincoking.loginOut()
                navi('/login')
              }
            })
          }
        },
      ]}
    />
  );


  const menu1 = (
    <Menu
      items={[
        {
          label: '我的建议',
          key: '1',
          icon: <UserOutlined />,
          onClick:()=>setModal1Open(true)
        },
      ]}
    />
  );

  const menu2 = (
    <img src='https://cc3ihai5g6h4sltf7akg.baseapi.memfiredb.com/storage/v1/object/public/static/赞助二维码.jpg' style={{width:'5rem'}}/>
  );


  //观看历史记录
  const hisdata=(
    <div className='historycontent'>
      {
        userData.history?
        historydata.map(item=>
          <a key={item.id} onClick={()=>window.open(item.link,'_black')}>
            <img src={item.img}/>
            <p>
              <strong>{item.text}</strong>
              <span>{item.time}</span>
            </p>
          </a>
      ):<h1 style={{width:'100%',color:'var(--greyDark)'}}>暂无数据</h1>
      }
    </div>
    
  )
  //轮播图图片
  async function RotationImgs(){
    setloading(true)  //页面loading
    const { data, error } = await supabase
      .from('RotationImgs')
      .select('*')
    setRotationImg(data)
  }




// 头部搜索框
let timer
function headerinputchange(value){
  clearTimeout(timer)
  timer=setTimeout(() => {
    // console.log(value);
  }, 700);

}

// 提交触发
let searchdata=JSON.parse(getToken('search'))  //获取历史记录
function headersubmit(value){
  if(searchdata==null){
    searchdata=[]
  }
  // console.log(searchdata,11111);
  setToken('search',JSON.stringify([...searchdata,value]))
  navi(`/search?search=${value}`)
}
// 清除一条记录
function searchhistory(e){
  setToken('search',JSON.stringify(searchdata.filter(item=>item!==e.target.id)))
  if(JSON.parse(getToken('search')).length==0) removeToken('search')  //如果数组里无数据就移除，因为空数组默认为true
  setsearchstate(!searchstate)
}
function historySearch(e){
  // console.log(e.target.childNodes[1].id)
  navi(`/search?search=${e.target.childNodes[1].id}`)
}
//内容区所有数据
async function contentdata(){
  let { data, error } = await supabase
      .from('contentHighestscore')
      .select('*')

  setContentData(e=>{return {...e,contentHighestscore:data}})  //数据量比较大时，应用回调方式才能获取最新数据
}
async function contentViolation(){
  let { data:test3 } = await supabase
  .from('contentViolation')
  .select('*')

  setContentData(e=>{return {...e,contentViolation:test3}})
  setloading(false)
}
async function contentCausedepression(){
  let { data:test2 } = await supabase
  .from('contentCausedepression')
  .select('*')

  setContentData(e=>{ return {...e,contentCausedepression:test2}})
}
async function contentfavourite(){
  let { data:test1 } = await supabase
  .from('contentfavourite')
  .select('*')
  setContentData(e=>{return {...e,contentfavourite:test1}})
}


// 聊天框
  // 获取聊天框数据
  async function getchat(){
    let { data, error } = await supabase
    .from('chat')
    .select('*')
    //对时间进行排序
    data=data.sort((a,b)=>a.time < b.time ? 1 : -1);
    setchat(data)
  }
  function chatchange(e){
    setchatdata(e)
  }
  // 聊天框提交
  async function chatsubmit(value){
    setchatloading(true)
    let { data, error } = await supabase
        .from('chat')
        .insert([
          {data:value,time:dayjs().format('YYYY-MM-DD HH:mm')}
        ]);
    setchatloading(false)
    setchatdata('')
  }
  const text=<Inputs text='发送' placeholder='请输入内容' onsubmit={chatsubmit} onchange={chatchange} defaultvalue={chatdata} loading={chatloading}/>
  const content = (
    <ul>
      {chat.map(item=><li key={item.id}><pre>{item.data}</pre><div><span>{item.time}</span></div></li>)}
    </ul>
  );


  // 热门搜索数据
  async function hotSearch(){
    let { data, error } = await supabase
      .from('HotSearch')
      .select('*');
      setHotData(data)
  }

  
  async function RecommendedCard(){  //推荐卡
    let { data, error } = await supabase
      .from('recommended_card')
      .select('*');
      // console.log(data)
      setrecommendedcard(data)

  }


  //记录点击历史
  async function recordHistory(id){
    // 这里可以给一个节流，用户如果点击后立马关闭(点错了)就不发送请求了
    const user=JSON.parse(getToken('user'))
      const {data,err}=await supabase
      .from('user')
      .update({...userData,history:`${id},${dayjs().format('MM-DD HH:mm')}/${userData.history?userData.history:''}`})
      .match({username:user.username})  //根据账号查找到对应的用户
    // console.log(data)
    // sethistorydata([...historydata,data[0]])
    usermessage()
    
  }

  useEffect(()=>{

    console.error('控制台轮播图报错（currentSlide，slideCount）因为左右箭头的问题，不影响正常使用。速度慢是因为整个网站只用了10元上线，所以这不是很正常吗')
    setTimeout(() => {
    console.error('控制台轮播图报错（currentSlide，slideCount）因为左右箭头的问题，不影响正常使用。速度慢是因为整个网站只用了10元上线，所以这不是很正常吗')
      
    }, 1000);
    hotSearch()  
    RotationImgs()
    usermessage()
    RecommendedCard()
    getchat()

    // 内容区
    contentdata()
    contentfavourite()
    contentCausedepression()
    contentViolation()

  //搜索框内容获取真实dom(都是用js写的)
  // 必须放在useEffect里，因为dom渲染完后才能获取节点，否则会报null的错误
  let con=document.querySelector('.search__input')
  let a=document.querySelector('.headcontent')
  con.addEventListener('focus',()=>{
    a.style.display='block'
  })
  con.addEventListener('blur',()=>{
    setTimeout(() => {  //因为点击直接隐藏了，不跳转，所以让他晚点隐藏
      a.style.display='none'
    }, 300);
    
  })
  
// as()

  },[chatloading])  //每当发送聊天，实时获取最新数据


  // async function as(){
    // const {data,err}=await supabase
    //   .from('contentCausedepression')
    //   .insert([
    //     {id:'9cf8c52e-52f6-4f28-aebe-8f59d483b43d',text:'未闻花名',link:'https://www.bilibili.com/bangumi/play/ss835?spm_id_from=333.337.0.0',src:'https://cc3ihai5g6h4sltf7akg.baseapi.memfiredb.com/storage/v1/object/public/ContentImgs/间谍过家家.jpeg'},
    //     {id:'c709f2bb-60a6-4f8a-b436-0347c633002d',text:'天使的心跳',link:'https://www.bilibili.com/bangumi/play/ss959?spm_id_from=333.337.0.0',src:'https://cc3ihai5g6h4sltf7akg.baseapi.memfiredb.com/storage/v1/object/public/ContentImgs/天使的心跳.jpeg'},
    //     {id:'e796da59-2c25-4c55-a1dc-44b8cd23a93a',text:'可塑性记忆',link:'https://www.bilibili.com/bangumi/play/ss1552?spm_id_from=333.337.0.0',src:'https://cc3ihai5g6h4sltf7akg.baseapi.memfiredb.com/storage/v1/object/public/ContentImgs/可塑性记忆.jpeg'},
    //     {id:'290c5f43-17a0-413e-a8da-ad3a25299c74',text:'clannad',link:'https://www.bilibili.com/bangumi/play/ss1177?spm_id_from=333.337.0.0',src:'https://cc3ihai5g6h4sltf7akg.baseapi.memfiredb.com/storage/v1/object/public/ContentImgs/clannad.jpeg'},
    //   ])
  // }


  return (
    <div className='home'>
        <header>
            <h1><a href='#' title='LOVE is only' onClick={()=>navi('/')}><img alt='LOVE is going' src={Img} /></a></h1>
            
            
              <Dropdown overlay={menu1} placement="bottom">
                <div><SendOutlined style={{fontSize:'1.2rem'}}/><span>建议</span></div>
              </Dropdown>
              <Dropdown overlay={menu2} placement="bottom">
                <div><RedEnvelopeOutlined style={{fontSize:'1.2rem'}}/><span>赞助</span></div>
              </Dropdown>

           

            <div className='headsearch'>
              <Inputs icon={<SearchOutlined />} text='搜索' placeholder='请输入搜索内容' onsubmit={headersubmit} onchange={headerinputchange} loading={headerloading}/>
              <div className='headcontent'>
                {
                  searchdata?         // 有数据显示，无数据隐藏
                  <div className='headhistory'>  
                    <div><strong>搜索历史</strong><span onClick={()=>{removeToken('search');setsearchstate(!searchstate)}}>清空</span></div>
                    <ul>
                      {searchdata.map((item,index)=><li onClick={(e)=>historySearch(e)} key={index}>{item}<span id={item} onClick={(e)=>searchhistory(e)}>x</span></li>)}
                    </ul>
                  </div>:''
                }
                <div className='headhot'>
                  <strong>热搜</strong>
                  <ul>
                    {
                      HotData.map((item,index)=>{
                        index=index+1
                        return <a key={item.id} href={item.link} onClick={()=>recordHistory(item.id)} target='_blank'><li><strong>{index}</strong>{item.text}</li></a> 
                      })
                    }
                  </ul>
                </div>
              </div>
            </div>

     

            <Dropdown overlay={menu1} placement="bottom">
              <div><SendOutlined style={{fontSize:'1.2rem'}}/><span>建议</span></div>
            </Dropdown>
            <Dropdown overlay={hisdata} placement="bottom" className='historydata' getPopupContainer={()=>document.querySelector('.historydata')}>
              <div><RedEnvelopeOutlined style={{fontSize:'1.2rem'}}/><span>历史</span></div>
            </Dropdown>
            <Dropdown overlay={menu2} placement="bottom">
              <div><RedEnvelopeOutlined style={{fontSize:'1.2rem'}}/><span>赞助</span></div>
            </Dropdown>
            

            <Dropdown.Button getPopupContainer={()=>document.querySelector('.ant-dropdown-button')} overlay={menu} placement="bottom" icon={<Avatar src={userData.icon}  alt='暂无头像' icon={<UserOutlined />} />}>
            
              {
                userData?userData.name:<span onClick={()=>navi('/login')}>去登陆</span>
              }
            </Dropdown.Button>

      
        </header>

        {/* 用来阻止home整体下移 */}
        <div style={{height:'7rem'}}></div>
        
        <div className='container'>
          {/* 骨架屏 */}
          {
            RotationImg.length?'':<Space style={{display:'flex',width:'100%',height:'20rem',justifyContent:'space-between'}}>
                <Skeleton.Image active={true} />
                <Skeleton.Node active={true}>
                  <DotChartOutlined
                  style={{fontSize: 40,color: '#bfbfbf',
                    }}
                  />
                </Skeleton.Node>
              </Space>
          }
          
          {/* 轮播图 */}
          <Carousel effect="fade" autoplay arrows prevArrow={<ArrowLeftOutlined />} nextArrow={<ArrowRightOutlined />} pauseOnDotsHover={true} >
            {
              RotationImg.map(item=>
              
                <a key={item.id} href={item.link} target='_blank' onClick={()=>recordHistory(item.id)}><h3><img src={item.img}/></h3></a>
              )
            }
          </Carousel>
          {/* 推荐卡 */}
          <div className='recommended-card'>
            {
              recommendedcard.map(item=><a key={item.id} onClick={()=>recordHistory(item.id)} target='_blank' href={item.link}><div><img src={item.img}/></div><p>{item.text}</p></a>)
            }
          </div>



        </div>
        {/* 内容区 */}
        <div className='content'>
                                                        {/* 这里不用navi，因为要跳转到新页面 */}
          <SectionTitle left='小编推荐' right={<a onClick={(e)=>{navi('/morecontent?select=小编');e.preventDefault()}} href='#'>更多</a>}></SectionTitle>
          <FourGrid data={ContentData.contentfavourite} recordHistory={recordHistory}/>
        </div>
        
        <div className='content'>
          <SectionTitle left='最高评分' right={<a onClick={(e)=>{navi('/morecontent?select=最高评分');e.preventDefault()}} href='#'>更多</a>}></SectionTitle>
          <FourGrid data={ContentData.contentHighestscore} recordHistory={recordHistory}/>
        </div>

        <div className='content'>
          <SectionTitle left='最致郁' right={<a onClick={(e)=>{navi('/morecontent?select=致郁');e.preventDefault()}} href='#'>更多</a>}></SectionTitle>
          <FourGrid data={ContentData.contentCausedepression} recordHistory={recordHistory}/>
        </div>

        <div className='content'>
          <SectionTitle left='大尺度' right={<a onClick={(e)=>{navi('/morecontent?select=大尺度');e.preventDefault()}} href='#'>更多</a>}></SectionTitle>
          <FourGrid data={ContentData.contentViolation} recordHistory={recordHistory}/>
        </div>

        <h1 style={{margin:'3rem'}}>我是有底线的，哼~~~</h1>
        {/* 建议弹出框 */}
        <Modal
          title="请给出您的宝贵建议(这对我们很重要)"
          style={{
            top: 20,
          }}
          visible={modal1Open}
          onOk={() =>proposal()}
          onCancel={() => setModal1Open(false)}
          >
          <TextArea
            showCount
            placeholder='请在这里留下您的宝贵建议'
            maxLength={100}
            style={{
              height: 120,
            }}
            onChange={e=>setproposaltext(e.target.value)}
          />
          <span style={{marginRight:'1rem'}}>请给我们的网站打分:</span>
          <Rate character="好" style={{color:'var(--primary-dark)'}} allowHalf value={start} tooltips={starttext} onChange={(value)=>setstart(value)}/>
        </Modal>

        {/* 聊天 */}
        <Popover autoAdjustOverflow='false' placement="topRight" title={text} content={content} trigger="click" overlayInnerStyle={{width:'20rem'}}>
          <Button className='chat'>聊天</Button>
        </Popover>

        {/* 置顶 */}
        <BackTop visibilityHeight={600}>
          <span>UP</span>
        </BackTop>



        {loading?<Loading/>:''}
        <Outlet/>
    </div>
  )
}
export default Home
